<template>
  <div>
    <!-- 搜索框和过滤框 -->
    <div class="search">
      <form-input
        class="searchInput"
        placeholder=" 输入要查找的学科名称"
        v-model="filterText"
      >
      </form-input>
      <el-cascader
        placeholder="请选择学科"
        :options="FilterList"
        filterable
        :show-all-levels="false"
        :props="FilterProps"
        @change="result2"
        clearable
        v-model="nowSelect"
      ></el-cascader>
    </div>
    <!-- 增加、删除操作 -->
    <div class="operation">
      <button class="add" @click="formShow = true">增加</button>
    </div>
    <!-- 增加表单 -->
    <div class="SpringFrame" v-show="formShow">
      <div class="form">
        <i class="el-icon-close" id="close" @click="close()"></i>
        <f-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <form-item label="学科名称" prop="name" class="objectName">
            <form-input v-model="ruleForm.name" name="name"></form-input>
          </form-item>
          <form-item label="学科介绍" prop="type">
            <form-input
              type="textarea"
              v-model="ruleForm.type"
              name="introduce"
              resize=none
            ></form-input>
          </form-item>
          <form-item>
            <msg-button type="primary" @click="submitForm('ruleForm'), Show()"
              >添加</msg-button
            >
            <msg-button @click="resetForm('ruleForm')">重置</msg-button>
          </form-item>
        </f-form>
      </div>
    </div>
    <!-- 内容展示区域 -->
    <div class="content">
      <div class="exhibition">
        <el-table
          id="table"
          :data="
            tables.slice((currentPage - 1) * pageSize, currentPage * pageSize)
          "
          border
          style="width: 100%"
        >
          <el-table-column
            fixed
            prop="subjectId"
            label="ID"
            width="80px"
            align="center"
          >
          </el-table-column>
          <el-table-column fixed prop="name" label="学科名称" width="300px">
            <template slot-scope="scope">
              <div slot="reference" class="twoLineCls">
                {{ scope.row.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="introduce" label="学科介绍">
            <template slot-scope="scope">
              <el-popover
                placement="top-start"
                title="学科介绍"
                width="200"
                trigger="hover"
                :content="scope.row.introduce"
              >
                <div slot="reference" class="twoLineCls">
                  {{ scope.row.introduce }}
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="100px"
          >
            <template slot-scope="scope">
              <alter-button
                type="text"
                size="medium"
                @click="handleEdit(scope.$index, scope.row)"
                class="el-icon-edit"
              ></alter-button>
              <alter-button
                @click.native.prevent="
                  deleteRow(scope.$index, scope.row), open()
                "
                type="text"
                size="medium"
                class="el-icon-delete"
              >
              </alter-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 修改表单 -->
    <div class="editBackground" v-show="editShow">
      <div class="editTable">
        <f-form
          ref="form"
          :model="sizeForm"
          label-width="80px"
          size="medium"
          class="editForm"
          @submit.native.prevent
        >
          <form-item label="学科名称" prop="name">
            <form-input v-model="sizeForm.name" name="name"></form-input>
          </form-item>
          <form-item label="学科介绍" prop="introduce">
            <form-input
              type="textarea"
              v-model="sizeForm.introduce"
              name="introduce"
              resize=none
            ></form-input>
          </form-item>
          <form-item size="large">
            <alter-button type="primary" @click="onSubmit(), Show()"
              >修改</alter-button
            >
            <alter-button @click="cancle">取消</alter-button>
          </form-item>
        </f-form>
      </div>
    </div>
    <!-- 展示分页 -->
    <div class="paging">
      <el-pagination
        background
        :page-size="pageSize"
        :current-page="currentPage"
        layout="prev, pager, next"
        :total="tables.length"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import "@/assets/css/resourceManegement.css";
import axios from "axios";
import $ from "jquery";
import { mapMutations } from "vuex";
import {
  SearchSubjectByIdAPI,
  SearchAllSubjectAPI,
  UpdateSubjectAPI,
  DeleteSubjectAPI,
} from "@/api/utils/index";
export default {
  mounted() {
    this.result();
  },
  data() {
    return {
      //搜索框
      filterText: "",
      // 是否全选
      ifchekAll: false,
      checkbox: false,
      //复选框
      checked: false,
      // 表单配置
      ruleForm: {
        name: "",
        type: "",
      },
      //过滤框
      nowSelect: "",
      //过滤框下拉内容
      FilterList: [],
      FilterProps: {
        value: "subjectId",
        label: "name",
        children: null,
      },
      tableData: [],
      formShow: false,
      //修改表单中的内容
      sizeForm: {
        name: "",
        introduce: "",
      },
      ifRequest: true,
      editShow: false,
      currentPage: 1,
      pageSize: 5,
      // 表单中的相关规则配置
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        type: [{ required: true, message: "请填写学科介绍", trigger: "blur" }],
      },
    };
  },
  methods: {
    // 页面刷新
    ...mapMutations("Refresh", { Show: "Show" }),
    async result2(v) {
      return SearchSubjectByIdAPI(v).then((res) => {
        if (res.data.flag) {
          this.tableData = [];
          //结果为对象所以要用 push 到数组中
          this.tableData.push(res.data.data);
        }
      });
    },
    // 过滤
    async result() {
      return SearchAllSubjectAPI().then((res) => {
        if (res.data.flag) {
          //结果为对象所以要用 push 到数组中
          //  this.tableData.push(response.data.data)
          this.FilterProps.value = "subjectId";
          this.FilterProps.children = null;
          this.tableData = this.FilterList = res.data.data;
        }
      });
    },
    // 表单方法
    submitForm(formName) {
      //表单验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //获取所有的表单中的内容
          var params = $(".demo-ruleForm").serializeArray();
          //    console.log(params);
          //把从表单获取过来的值存储为对象
          let array = {};
          params.forEach((element) => {
            array[element.name] = element.value;
          });
          //把对象转换为 jsonp 格式
          array = JSON.stringify(array);
          axios({
            method: "post",
            headers: {
              "Content-Type": "application/json",
            },
            url: "http://124.71.219.15:8083/management_system/subject/insert",
            data: array,
          }).then((response) => {
            if (response.data.flag) {
              // alert('添加成功！')
              // $('.demo-ruleForm').reset()
              this.formShow = false;
              this.PageRefresh();
              this.$message.success("增加成功!");
            } else {
              this.PageRefresh();
              this.$message.error(response.data.errorMsg);
            }
          });
        }else{
          this.PageRefresh();
          this.$message.error("表单有空值，增加失败！")
        }
      });
    },
    // 编辑按钮
    handleEdit(index, rows) {
      this.editShow = true;
      this.sizeForm.name = rows.name;
      this.sizeForm.introduce = rows.introduce;
      this.currentId = rows.subjectId;
      // console.log(index,rows);
    },
    //修改表单提交
    async onSubmit() {
      var params = $(".editForm").serializeArray();
      let array = {};
      array.subjectId = this.currentId;
      //判断表单不能为空，且获取到数据
      params.forEach((element) => {
        if (element.value == "") {
          this.ifRequest = false;
          this.open4();
          this.PageRefresh();
        } else {
          // 把表单中获取到的值转化为对象形式
          array[element.name] = element.value;
        }
      });
      //把对象转换为 jsonp 格式
      if (this.ifRequest) {
        array = JSON.stringify(array);
        // console.log(array);
        // 进行修改操作
        return UpdateSubjectAPI(array).then((res) => {
          if (res.data.flag) {
            this.editShow = false;
            this.PageRefresh();
            this.$message.success("修改成功!");
          } else {
            this.editShow = false;
            this.PageRefresh();
            this.$message.error(res.data.errorMsg);
          }
        });
      }
    },
    //删除操作
    // 获取删除的对象对应的id、名字等
    deleteRow(index, rows) {
      // console.log(index,rows);
      //解决中文乱码
      // console.log(window.decodeURIComponent(rows.name));
      this.subjectName = rows.name;
    },
    //执行删除操作
    async ExecuteDelete() {
      return DeleteSubjectAPI(this.subjectName).then((res) => {
        if (res.data.flag) {
          this.Show();
          this.editShow = false;
          this.PageRefresh();
          this.$message.success("删除成功!");
        } else {
          this.$message.error("删除失败!");
        }
      });
    },
  },
};
</script>
<style scoped>
/* 设置级联框的高度 */
.search /deep/ .el-cascader {
  height: 40px;
}
/* 增加表单样式 */
.form {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 670px;
  max-height: 650px;
  background-color: white;
  padding-left: 135px;
  padding-top: 30px;
  box-sizing: border-box;
  border-radius: 15px;
}
.form /deep/form input {
  margin: -3px;
}
.form /deep/.el-form demo-ruleForm {
  width: 450px;
  height: 500px;
}
.form /deep/.el-form-item__content {
  width: 300px;
}
#close {
  position: absolute;
  top: 5px;
  right: 5px;
  font-size: 20px;
  cursor: pointer;
  color: #ccc;
}
/* 修改表单 */
.editBackground {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 98;
  background-color: rgba(0, 0, 0, 0.5);
}
.editTable {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 588px;
  max-height: 512px;
  padding: 10px 67px;
  background-color: white;
  border-radius: 10px;
  box-sizing: border-box;
  z-index: 99;
}
.editTable /deep/.el-input {
  width: 40%;
}
.editTable /deep/.el-textarea {
  width: 65%;
}
.paging {
  width: 100%;
  height: 30px;
  margin-bottom: 0;
  text-align: center;
}
.twoLineCls {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
}
.searchInput /deep/.el-input__inner {
  border: 3px solid #dcdfe6;
}
.search /deep/.el-cascader .el-input .el-input__inner {
  border: 3px solid #dcdfe6;
}
.el-table--border {
  border: 3px solid #ebeef5;
}
.exhibition /deep/.el-table .cell {
  color: #666;
}
.exhibition /deep/.twoLineCls {
  color: black;
}
.exhibition /deep/.el-table th.el-table__cell,
.exhibition /deep/.el-table tr,
.exhibition /deep/.el-table {
  background-color: rgba(255, 255, 255, 0.3);
}
</style>